package top.jacktgq.itheima.nio.file;

import org.junit.Test;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author CandyWall
 * @Date 2021/3/19--5:14
 * @Description 测试jdk1.7后提供的文件遍历api
 */
public class TestFilesWalkFileTree {
    @Test
    /**
     * 遍历某个文件夹下的所有文件夹和文件
     */
    public void testWalkFileTree() throws IOException {
        AtomicInteger dirCount = new AtomicInteger();
        AtomicInteger fileCount = new AtomicInteger();

        Files.walkFileTree(Paths.get("D:\\jdk\\jdk1.8.0_131"), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                System.out.println("--->" + dir);
                dirCount.incrementAndGet();
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                System.out.println(file);
                fileCount.incrementAndGet();
                return super.visitFile(file, attrs);
            }
        });
        System.out.println("文件夹数：" + dirCount + "，文件数：" + fileCount);
    }

    @Test
    /**
     * 按条件遍历：遍历文件夹下面的jar包
     */
    public void testWalkFileTreeByCondition() throws IOException {
        AtomicInteger fileCount = new AtomicInteger();

        Files.walkFileTree(Paths.get("D:\\jdk\\jdk1.8.0_131"), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toString().endsWith(".jar")) {
                    fileCount.incrementAndGet();
                }
                return super.visitFile(file, attrs);
            }
        });
        System.out.println("jar包数：" + fileCount);
    }

    @Test
    public void testFilesCopy() throws IOException {
        String source = "./tmp";
        String target = "./tmp1";

        Files.walk(Paths.get(source)).forEach(path -> {
            // 获取源文件夹的名称
            String sourceDirName = source.substring(source.lastIndexOf("/") + 1);
            // 获取目标文件夹的名称
            String targetDirName = target.substring(target.lastIndexOf("/") + 1);
            try {
                String targetName = path.toString().replace(sourceDirName, targetDirName);
                System.out.println(sourceDirName + ", " + targetDirName + ", " + targetName);
                // 是目录
                if (Files.isDirectory(path)) {
                    // 创建目录
                    Files.createDirectory(Paths.get(targetName));
                }
                // 普通文件
                else if(Files.isRegularFile(path)) {
                    // 复制文件
                    Files.copy(path, Paths.get(targetName));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }


    @Test
    /**
     * 删除目录
     */
    public void testDeleteDir() throws IOException {
        // 如果待删除的目录中有文件，无法直接删除，会报 java.nio.file.DirectoryNotEmptyException: .\tmp1
        //Files.delete(Paths.get("./tmp1"));
        // 需要先遍历待删除的文件夹，删除子 文件和文件夹
        Files.walkFileTree(Paths.get("./tmp1"), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                System.out.println("--->进入目录：" + dir);
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                System.out.println("删除文件：" + file);
                Files.delete(file);
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                System.out.println("删除目录：" + dir);
                Files.delete(dir);
                return super.postVisitDirectory(dir, exc);
            }
        });
    }
}
